import { Component, OnInit } from '@angular/core';
import {Message, TreeNode} from 'primeng/primeng';
import {MaintenanceService} from '../../maintenance.service';
import {ActivatedRoute, Router} from '@angular/router';
import {StorageService} from '../../../services/storage.service';
import {PublicService} from '../../../services/public.service';
import {PUblicMethod} from '../../../services/PUblicMethod';
import {EventBusService} from '../../../services/event-bus.service';
import {MatenanceObjModel} from '../../matenanceObj.model';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-malfunction-up',
  templateUrl: './malfunction-up.component.html',
  styleUrls: ['./malfunction-up.component.scss']
})
export class MalfunctionUpComponent implements OnInit {

    formObj: MatenanceObjModel;
    options: Object = {
        'upgrade_reason': []
    };
    defaultOption: Object = {
        'upgrade_reason': null
    };
    display: boolean = false;
    filesTree4: TreeNode[] = [];
    selected: Array<any> = [];
    myForm: FormGroup;
    message: Message[] = [];               // 交互提示弹出框
    dispalyDep: boolean = false;

    constructor(private maintenanceService: MaintenanceService,
                private router: Router,
                private fb: FormBuilder,
                private publicService: PublicService,
                private activatedRouter: ActivatedRoute,
                private eventBusService: EventBusService) { }

    ngOnInit() {
        this.formObj = new MatenanceObjModel();
        this.getDepPerson();
        this.initOption();
        this.formObj.upgrade_reason = this.options['upgrade_reason'][0]['value'];
        this.formObj.upgrade_time = PUblicMethod.formateEnrtyTime(new Date());
        this.initForm();
        this.formObj.sid = this.activatedRouter.snapshot.paramMap.get('id');
        this.formObj.status = this.activatedRouter.snapshot.paramMap.get('status');
        this.maintenanceService.getFlowChart(this.formObj.status).subscribe(res => {
            this.eventBusService.maintenance.next(res);
        });
    }
    initOption() {
        this.options['upgrade_reason'] = [
            {label: '资源升级', value: '资源升级'},
            {label: '技术升级', value: '技术升级'}
        ];
        this.formObj.upgrade_reason = '资源升级';
    }
    goBack() {
        this.router.navigate(['../malfunctionOverview'], {relativeTo: this.activatedRouter});
    }
    getDepPerson(oid?) {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.options['departments'] = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.options['departments'] = newArray;
                this.formObj.processor_pid = newArray[0]['value']['pid'];
                this.formObj.processor = newArray[0]['value']['name'];
            }
        });
    }
    showTreeDialog( opType ) {
        switch (opType) {
            case 'department':
                this.display = true;
                this.publicService.getDepartmentDatas().subscribe(res => {
                    this.filesTree4 = res;
                });
        }

    }
    clearTreeDialog(opType) {
        switch (opType) {
            case 'department':
                this.formObj.processor = '';
                this.formObj.processor_pid = '';
                this.formObj.processor_org = '';
                this.formObj.processor_org_oid = '';
                break;
        }
    }
    closeTreeDialog() {
        this.display = false;
        this.formObj.processor_org = this.selected['label'];
        this.formObj.processor_org_oid = this.selected['oid'];
        this.getDepPerson(this.selected['oid']);
    }
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    addSelectedName() {
        (!this.formObj.upgrade_reason) && (this.formObj.upgrade_reason = this.defaultOption['upgrade_reason']);
        // (!this.formObj.processor) && (this.formObj.processor = this.defaultOption['processor']);
    }
    filterOptionName() {
        if (this.formObj.processor['name']) {
            this.formObj.processor = this.formObj.processor['name'];
        }
        if (this.formObj.upgrade_reason['value']) {
            this.formObj.upgrade_reason = this.formObj.upgrade_reason['value'];
        }
    }
    get acceptor() {
        // console.log('untouched', this.myForm.controls['content'].untouched);
        // console.log('required', this.myForm.controls['content'].hasError('required'));
        return this.myForm.controls['processor_org'].untouched && this.myForm.controls['processor_org'].hasError('required');
    }
    setValidators() {
        this.myForm.controls['processor_org'].setValidators([Validators.required]);
        this.myForm.controls['processor_org'].updateValueAndValidity();
    }
    initForm() {
        this.myForm = this.fb.group({
            'processor_org': '',
        });
    }
    onChange(event) {
        this.formObj.processor = event['value']['name'];
        this.formObj.processor_pid = event['value']['pid'];
    }
    submitTrick() {
        this.addSelectedName();
        this.filterOptionName();
        if (!this.formObj.processor_org && this.formObj.upgrade_reason === '技术升级') {
            this.showError();
            this.setValidators();
        }else {
            if (this.formObj.upgrade_reason === '资源升级') {
                this.formObj.processor = '';
                this.formObj.processor_pid = '';
                this.formObj.processor_org = '';
                this.formObj.processor_org_oid = '';
            }
            this.upPost(this.formObj);
        }
    }
    showError() {
        this.message = [];
        this.message.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }
    switchReason(event) {
        (event['value'] === '技术升级') && (this.dispalyDep = true);
        (event['value'] === '资源升级') && (this.dispalyDep = false);
    }
    upPost(paper) {
        this.maintenanceService.upTrick( paper ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
            }
        });
    }

}
